package com.zqs.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;

public class SingleConsumer {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] argv) throws Exception {
        //新建一个连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.115.208.45");
        factory.setUsername("MSNzqs");
        factory.setPassword("zqs0417");
        factory.setPort(5672);
        //连接工厂生成一个连接
        Connection connection = factory.newConnection();
        //通过连接生成一个通道
        Channel channel = connection.createChannel();
        //在连接中声明一个队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        //定义一个回调函数，当接收到消息时，执行该函数
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
        };
        //通过通道消费消息，并指定回调函数，当接收到消息时执行回调函数deliverCallback，从而输出消息队列中的消息
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
    }
}